package com.roc.web.action.estrn;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.AreaBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.EstrnStastics;
import com.roc.pojo.Operators;
import com.roc.pojo.TblTfrTrnLog;
import com.roc.service.EstrnStasticsService;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.ServiceException;
import com.roc.service.area.IAreaService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Component
@Scope("prototype")
@Namespace("/estrnlog")
public class EstrnStasticsAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(EstrnStasticsAction.class);
	
	private EstrnStasticsSearchCondition searchCondition;
	
	private InputStream excelFile;
	
	//收单事业部Id
	private static final String SD_SUPER_ID="40001";
	
	private static final String SD_ORG_CODE = "48502000";
	
	protected Map<String,String> tranMap = ConfigProperties.getSysDB1("TRANS_CD",false);
	
	@Autowired
	IPageService pagenitionService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired 
	private EstrnStasticsService estrnStasticsService;
	
	@Autowired
	IExcelService excelService;
	
 
	@Autowired
	private IAreaService areaService;
	
 
	@Action(value = "estrnStasticsInit", results = { @Result(name = "success", location = "/pages/estrn/estrnStastics.jsp"),
			@Result(name = "error", location = "/error.jsp")
	})
	public String estrnStasticsInit(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		org();
		return SUCCESS;
	}
	
	@Action(value = "queryEstrnStastics", results = { @Result(name = "success", location = "/pages/estrn/estrnStastics.jsp"),@Result(name = "error", location = "/error.jsp")
    })
	public String queryEstrnStastics(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		
		try {
			if(searchCondition==null){
				searchCondition=(EstrnStasticsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new EstrnStasticsSearchCondition();
				}
			}
			searchCondition.setOrgCode(SD_ORG_CODE);
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<TblTfrTrnLog> tftList = new ArrayList<TblTfrTrnLog>();
			dealTheSearchRsList(tftList,searchRsList);
			
			
		
			getRequest().setAttribute("tftList", tftList);
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			org();
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+tftList.size()+"】条记录");
		} catch (Exception e) {
			logger.error("查询交易统计信息异常："+e.getMessage());
		}
		return SUCCESS;
	}
	
	@Action(value = "summaryEstrnStastics", results = { @Result(name = "success", location = "/pages/estrn/estrnStastics.jsp"),@Result(name = "error", location = "/error.jsp")
    })
	public String summaryEstrnStastics(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		try {
			if(searchCondition==null){
				searchCondition=(EstrnStasticsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new EstrnStasticsSearchCondition();
				}
			}
			searchCondition.setOrgCode(SD_ORG_CODE);
			List<EstrnStastics> esList = estrnStasticsService.queryEstrnStasticsList(searchCondition);
			getRequest().setAttribute("esList", esList);
			org();
			setSearchToConditionSession(searchCondition);
		} catch (ServiceException e) {
			logger.error("交易统计汇总异常");
		}
		return SUCCESS;
	}
	
	@Action(value="exportEstrnStastics",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/estrn/estrnStastics.jsp") })
	public String exportEstrnStastics(){
		
		try {
			if(searchCondition==null){
				searchCondition=(EstrnStasticsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new EstrnStasticsSearchCondition();
				}
			}
			searchCondition.setOrgCode(SD_ORG_CODE);
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<TblTfrTrnLog> tftList = new ArrayList<TblTfrTrnLog>();
			Map<String, String> summaryMap = dealTheSearchRsListForExport(tftList,searchRsList);
			
			SXSSFWorkbook work=excelService.exportTransStastics(tftList,searchCondition.getMinDate(),searchCondition.getMaxDate(),summaryMap);

			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();
			
		} catch (Exception e) {
			logger.error("导出交易统计信息异常："+e.getMessage());
		}
		return SUCCESS;
	}
	
	private Map<String,String> dealTheSearchRsListForExport(List<TblTfrTrnLog> tftList,
			List<Object> searchRsList) {
		String tzAmt = "0";
		String toAmt = "0";
		Map<String,String> resMap = new HashMap<String, String>(); 
	    Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
//	    Map<String, String> transTypes=ConfigProperties.getTransTypes();
	    
		if(searchRsList!=null&&searchRsList.size()>0){
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				TblTfrTrnLog t = new TblTfrTrnLog();
				t.setCompanyName(Constance.Null2EmptyTrim(obj[0]));
				t.setOneAgentName(Constance.Null2EmptyTrim(obj[1]));
				t.setTransDt(Constance.Null2EmptyTrim(obj[4]));
				t.setCardType(Constance.Null2EmptyTrim(obj[5]));
				String maTranCd = Constance.Null2EmptyTrim(obj[3]);
				t.setTransInf(tranMap.get(maTranCd));
				String tra = Constance.Null2EmptyTrim(obj[2]);
				if("".equals(tra)){
					t.setTransAt("0.00");
				}else{
					BigDecimal btra = new BigDecimal(tra);
					BigDecimal bb = new BigDecimal(100);
					BigDecimal bres = btra.divide(bb,2,BigDecimal.ROUND_HALF_UP); 
					t.setTransAt(bres.toString());
				}
				if("1171".equals(maTranCd)){
					tzAmt = new BigDecimal(tzAmt).add(new BigDecimal(t.getTransAt())).toString();
				}
				if("1011".equals(maTranCd)){
					toAmt = new BigDecimal(toAmt).add(new BigDecimal(t.getTransAt())).toString();
				}
				
				String posEntrymd = Constance.Null2EmptyTrim(obj[6]);
				t.setPosEntryMdCd(posEntrymd);
				if(posEntrymd.length()<3){
					t.setPosEntryMdCdName("未知");
				}else if("02".equals(posEntrymd.substring(0, 2))){
					t.setPosEntryMdCdName("刷磁");
				}else{
					t.setPosEntryMdCdName("芯片");
				}
				
				tftList.add(t);
			}
		}
		
		resMap.put("tzAmt", tzAmt);
		resMap.put("toAmt", toAmt);
		return resMap;
	}
	
	private void dealTheSearchRsList(List<TblTfrTrnLog> tftList,
			List<Object> searchRsList) {
	    Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
//	    Map<String, String> transTypes=ConfigProperties.getTransTypes();
	    
		if(searchRsList!=null&&searchRsList.size()>0){
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				TblTfrTrnLog t = new TblTfrTrnLog();
				t.setCompanyName(Constance.Null2EmptyTrim(obj[0]));
				t.setOneAgentName(Constance.Null2EmptyTrim(obj[1]));
				t.setTransDt(Constance.Null2EmptyTrim(obj[4]));
				t.setCardType(Constance.Null2EmptyTrim(obj[5]));
				String maTranCd = Constance.Null2EmptyTrim(obj[3]);
				t.setTransInf(tranMap.get(maTranCd));
				String tra = Constance.Null2EmptyTrim(obj[2]);
				if("".equals(tra)){
					t.setTransAt("0.00");
				}else{
					BigDecimal btra = new BigDecimal(tra);
					BigDecimal bb = new BigDecimal(100);
					BigDecimal bres = btra.divide(bb,2,BigDecimal.ROUND_HALF_UP); 
					t.setTransAt(bres.toString());
				}
				
				String posEntrymd = Constance.Null2EmptyTrim(obj[6]);
				t.setPosEntryMdCd(posEntrymd);
				if(posEntrymd.length()<3){
					t.setPosEntryMdCdName("未知");
				}else if("02".equals(posEntrymd.substring(0, 2))){
					t.setPosEntryMdCdName("刷磁");
				}else{
					t.setPosEntryMdCdName("芯片");
				}
				
				tftList.add(t);
			}
		}
	}

	public void org(){
		try {
			String yesterday = DateUtil.getDate(new Date(), -1, "yyyyMMdd");
			String today = DateUtil.getDate(new Date(), 0, "yyyyMMdd");
			getRequest().setAttribute("yesterday", yesterday);
			getRequest().setAttribute("today", today);
			// 查询某个代理商的直属代理商
			List<AreaBean> areaCodeList = areaService.queryAllAreaInf();
			getRequest().setAttribute("areaCodeList", areaCodeList);
		} catch (Exception e) {
			logger.error("交易统计页面初始化异常："+e);
		}
	}
	

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_ESTRN_STASTICS, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (EstrnStasticsSearchCondition)getSession().getAttribute(SEARCH_SESSION_ESTRN_STASTICS);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public EstrnStasticsSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(EstrnStasticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	
	public String getExcelName() {
		String excelName="交易统计详情"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	

}
